package com.yzg.design;

import lombok.extern.slf4j.Slf4j;

/**
 * @author misterWei
 * @create 2020年05月16号:00点07分
 * @mailbox forcontinue@163.com
 * <p>
 * 使用wait & notify 使用三个线程 执行5次  abcabcabcabcabc
 */
@Slf4j(topic = "c.waitNotifyCrossOut")
public class WaitNotifyCrossOut {
    static final Object ROOM = new Object();
    public static void main(String[] args) {
        LoopPrint loopPrint = new LoopPrint();
        new Thread(()->{
            loopPrint.printf("a",1,2);
        },"t1").start();
        new Thread(()->{
            loopPrint.printf("b",2,3);
        },"t2").start();
        new Thread(()->{
            loopPrint.printf("c",3,1);
        },"t3").start();

    }

    /**
     * a 0 1
     * b 1 2
     * c 2 3
     * .
     */
    static class LoopPrint{
       int loopNumber = 5;
       int temp = 1;
        public void printf(String content,int prefix,int next){
            for (int i = 0; i < loopNumber; i++) {
                synchronized (ROOM){
                    while (temp != prefix){
                        try {
                            ROOM.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    temp = next;
                    ROOM.notifyAll();
                    System.out.print(content);
                }
            }
        }

    }

}
